package com.qymerge.manage.core.utils.aliyun;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

import java.io.ByteArrayInputStream;

/**
 * Desc 阿里云OSS
 * User qiuchen
 * Date 2015/4/27
 * Time 11:50
 */
public class OSSUploadUtil {

    private static OSSClient fileClient;

    /**
     * 上传文件
     *
     * @param text
     * @param cipther
     * @return
     */
    public static boolean uploadFile(String text, final String cipther) {
        return upload(AliyunConfig.Bucket.File, text, cipther);
    }

    private static boolean upload(AliyunConfig.Bucket bucket, String text, final String cipther) {
        return putObject(bucket, cipther, text, 0);
    }

    private static boolean putObject(AliyunConfig.Bucket bucket, String key, String text, int length) {
        try {
            // 初始化OSSClient
            OSSClient client = getClient(bucket);
            // 创建上传Object的Metadata
            ObjectMetadata meta = new ObjectMetadata();
            //设置文件类型
            meta.setContentType(bucket.getContentType());
            // 上传Object.
            PutObjectResult result = client.putObject(bucket.getName(), key, new ByteArrayInputStream(text.getBytes()), meta);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private static OSSClient getClient(AliyunConfig.Bucket bucket) {
        return getFileClient();
    }

    private static OSSClient getFileClient() {
        if (fileClient == null) {
            String accessKeyId = AliyunConfig.Amount.accessKeyId;
            String accessKeySecret = AliyunConfig.Amount.accessKeySecret;
            String endPoint = AliyunConfig.Bucket.File.getEndpoint();
            fileClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
        }
        return fileClient;
    }

    public static void main(String[] args) {
        uploadFile("aaaaaaaaaaabbbbbbbbbbbcccccccccccc","area/11.json");
    }

}
